<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
      Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
      给定一个整数数组 nums 和一个整数 k，找到三个长度为 k 且总和最大的非重叠子数组并返回它们。 将结果作为索引列表返回，表示每个间隔的起始位置（0 索引）。 如果有多个答案，则返回字典序最小的一个。 
     */
    /**
     * 滑动窗口
     * 
     * @param {number[]} nums
     * @param {number} k
     * @return {number[]}
     */
    var maxSumOfThreeSubarrays = function(nums, k) {
      let maxsum1 = 0, maxsum12 = 0, maxsum123 = 0
      let sum1 = 0, sum2 = 0, sum3 = 0
      let ans = []
      // 初始窗口
      
      for(let i=2*k; i<nums.length; i++){
        sum1 += nums[i-(2*k)]
        sum2 += nums[i-k]
        sum3 += nums[i]
        // 大于3k-1之后就需要移动窗口
        if(i >= 3*k-1){
          console.log("进来的"+i)
          if(sum1 > maxsum1){ //1最大值
            ans[0] = i-(3*k)-1 //记住1的位置
            maxsum1 = sum1
          }
          if(maxsum1+sum2 > maxsum12){ //1和2最大值
            ans[1] = i-(2*k)-1 // 记住2的位置
            maxsum12 = maxsum1+sum2

          } 
          if(maxsum12+sum3 > maxsum123){ // 123的最大值
            ans[2] = i-k-1 //记住3的位置
            maxsum123 = maxsum12+sum3
          }

          // 最后减去第一位的值，下次循环再加上下一位(窗口)
          sum1 -= nums[i-(3*k)-1]
          sum2 -= nums[i-(2*k)-1]
          sum3 -= nums[i-k-1]
        }
        console.log(i)
        console.log(ans)
      }
      return ans
    };
    console.log(maxSumOfThreeSubarrays([1,2,1,2,6,7,5,1],2))
  </script>
</body>
</html>